﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Possan.Localization;
using System.Globalization;

namespace Loot
{
	public partial class Locales : Form
	{
		public ILibraryProvider Provider { get; set; }

		public Locales()
		{
			InitializeComponent();
			Provider = null;
			Load += new EventHandler(Locales_Load2);
		}

		void Locales_Load2(object sender, EventArgs e)
		{
			bindList();

			textBox1.Text = "";
			bindLocalePreview();
		}

		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
		}

		private void button1_Click(object sender, EventArgs e)
		{
			try
			{
				string loc = textBox1.Text.Trim();
				if (loc != "")
				{
					CultureInfo ci = CultureInfo.GetCultureInfo(loc);
					if (ci != null)
					{
						Provider.RegisterLocale(ci.Name);
					}
				}
			}
			catch (Exception z)
			{
			}
			bindList();
		}

		void bindList()
		{
			listBox1.Items.Clear();

			List<string> locales = Provider.GetLocales();
			foreach (string s in locales)
			{

				listBox1.Items.Add(s);
			}
		}


		private void listBox1_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				Close();
			}
			if (e.KeyCode == Keys.Delete)
			{
				if (listBox1.SelectedItem != null)
				{
					string loc = listBox1.SelectedValue.ToString();
					if (MessageBox.Show("Do you really want to delete the locale '" + loc + "'? All translations will be lost.", "Delete locale", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
					{
						Provider.DeleteLocale(loc);
						bindList();
					}
				}
			}
		}

		private void textBox1_KeyUp(object sender, KeyEventArgs e)
		{
			bindLocalePreview();
		}

		void bindLocalePreview()
		{
			string lab = "Invalid locale";
			string loc = textBox1.Text.Trim();
			if (loc != "")
			{
				try
				{
					CultureInfo ci = CultureInfo.GetCultureInfo(loc);
					if (ci != null)
					{
						lab = ci.DisplayName;
					}
				}
				catch (Exception)
				{
				}
			}
			label3.Text = lab;
		}
	}
}
